<?php

App::uses('Sanitize', 'Utility');
App::uses('ConnectionManager', 'Model');
App::uses('ClassRegistry', 'Utility');

/**
 * Custom Route class auto-enables /:page routes
 * Enables you to add new pages without having to manually specify a shortcut
 * route in your routes.php file
 *
 * To use, drop this into app/libs/routes/page_route.php and add
 * the following to the top of app/config/routes.php:
 *
 * App::import('Lib', 'routes/PageRoute');
 *
 * To trigger it, specify the routeClass in the route's options array, along
 * with the regex to allow subpages to be parsed:
 *
 * Router::connect('/:page', array(),
 *     array('routeClass' => 'PageRoute', 'page' => '[\/\w_-]+')
 * );
 *
 * Note that if a page has the same name as a controller/plugin, the page will
 * take precedence since it is included before Router::__connectDefaultRoutes()
 * is called.
 *
 * @author Jose Gonzalez (support@savant.be)
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 * @see CakeRoute
 */
class PageRoute extends CakeRoute {

    /**
     * Parses a string url into an array.  If a page is found, it is parsed into
     * the pass key in the route params
     *
     * @param string $url The url to parse
     * @return mixed false on failure, or an array of request parameters
     */
    public function parse($url) {
        //return parent::parse($url);
        $params = parent::parse($url);

        if (isset($params['page']) AND ! empty($params['page'])) {

            if ($params['controller'] == 'conteudo') {
                /*if (ClassRegistry::init('Conteudos.Conteudo')->find('count', array('conditions' => array('Conteudo.router' => $params['page']))) == 0) {
                    return false;
                }
                $params['pass'][0] = $params['page'];*/
            } else {
                if (ClassRegistry::init('Paginas.Pagina')->find('count', array('conditions' => array('Pagina.router' => $params['page']))) == 0) {
                    return false;
                }
                $params['pass'][0] = $params['page'];
            }
        }
        if (isset($params['categorias']) AND ! empty($params['categorias'])) {
            $params['pass'][0] = 'categorias';
            $params['pass'][1] = $params['categorias'];
        }
        unset($params['page']);
        unset($params['categorias']);
        return $params;
    }

}
